package com.demo.autotest.common.utils;

import com.demo.autotest.common.exception.FileException;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

public class FileUtils {
    // 文件操作类
    public static String saveFile(MultipartFile uploadFile, String dirPath, String name) {
        if (uploadFile == null) {
            return null;
        }
        File testDir = new File(dirPath);
        if (!testDir.exists()) {
            testDir.mkdirs();
        }
        String filePath = testDir + "/" + name;
        File file = new File(filePath);
        try {
            uploadFile.transferTo(file);
        } catch (IOException e) {
            throw new FileException("文件上传失败");
        }
        return filePath;
    }

    public static void deleteFile(String path) {
        File file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        String dir = path.substring(0, path.lastIndexOf("/"));
        File fileDir = new File(dir);
        if(fileDir.exists()){
            fileDir.delete();
        }
    }
}
